﻿using Pay.Core;
using Pay.DTO;
using Pay.IService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Web.Mvc;

namespace Pay.Token {
    public class GeneralController : Controller {
        protected userCookie currentUser;
        public GeneralController() {
        }
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) {
            return new JsonNetResult(data, behavior, contentType, contentEncoding);
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext) {
            //var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            //if (cookie != null) {
            //    var ticket = FormsAuthentication.Decrypt(cookie.Value);
            //    currentUser = ticket.UserData.ToObject<userCookie>();
            //}
            if (UserId > 0) {

                string actionName = filterContext.ActionDescriptor.ActionName;
                string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                if (controllerName != "User" && !(actionName == "Authentication" || actionName == "SetName")) {
                    var merchantService = DependencyResolver.Current.GetService<IMerchantService>();
                    var member = merchantService.GetTokenUser(UserId);
                    ViewData["TokenUser"] = member;
                    if (!member.is_verify_invitation_code) filterContext.Result = RedirectToAction("SetName", "User");
                    else {
                        //if (!member.is_verify_no_card) filterContext.Result = RedirectToAction("Authentication", "User");
                    }
                }
                if (controllerName == "Ad" && actionName == "WorldCupRecord") {
                    var playingService = DependencyResolver.Current.GetService<IPlayingService>();
                    playingService.DealUserGuess(UserId);
                }

            }
            base.OnActionExecuting(filterContext);
        }

        ///// <summary>
        ///// 创建用户Cookie
        ///// </summary>
        ///// <param name="name"></param>
        ///// <param name="userData"></param>
        ///// <param name="remember3day"></param>
        //protected void FormsCookieSave(string name, userCookie userData, bool remember3day) {
        //    DateTime issueDate = DateTime.Now;
        //    DateTime expiration = issueDate.Add(FormsAuthentication.Timeout);
        //    if (remember3day)
        //        expiration = issueDate.AddDays(3);
        //    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, issueDate, expiration, false, userData.ToJson());
        //    string hashTicket = FormsAuthentication.Encrypt(ticket);
        //    HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
        //    if (remember3day)
        //        userCookie.Expires = expiration;
        //    Response.Cookies.Add(userCookie);
        //}

        private long _user_id = 0;
        /// <summary>
        /// 登录用户ID
        /// </summary>
        protected long UserId {
            get {
                if (_user_id == 0 && User.Identity.IsAuthenticated) {
                    var identity = (User.Identity as ClaimsIdentity);
                    _user_id = long.Parse(identity.FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value);
                }
                return _user_id;
            }
        }
        /// <summary>
        /// 验证返回的错误提示
        /// </summary>
        public string ModelError {
            get {
                StringBuilder sb = new StringBuilder();
                foreach (var item in ModelState.Values) {
                    foreach (var er in item.Errors) {
                        if (!string.IsNullOrEmpty(er.ErrorMessage))
                            sb.Append(er.ErrorMessage + ",");
                        else
                            sb.Append(er.Exception.Message + ",");
                    }
                }
                return sb.ToString().TrimEnd(',');
            }
        }
        protected List<string> UploadList(string action_dir, string fileInput = "file", bool use_time = false) {
            List<string> paths = new List<string>();
            if (Request.Files.Count == 0)
                return null;
            if (Request.Files.Count > 0) {
                for (int i = 0; i < Request.Files.Count; i++) {
                    var file = Request.Files[i];
                    if (file == null)
                        return null;
                    var time = DateTime.Now.Date;

                    var dir = string.Format("{0}", action_dir).TrimEnd('/');
                    if (use_time) dir += "/" + (time.Ticks).ToString().TrimEnd('0');

                    string ext = Path.GetExtension(file.FileName);

                    byte[] file_byte = new byte[file.ContentLength];
                    file.InputStream.Read(file_byte, 0, file.ContentLength);

                    var fileType = FileValid.GetFileType(file_byte);
                    if (fileType != FileExtension.GIF && fileType != FileExtension.JPG && fileType != FileExtension.PNG)
                        throw new ServerErrorException("上传文件格式不正确");
                    MemoryStream mss = new MemoryStream(file_byte);
                    var oid = Guid.NewGuid().ToString("N");
                    var path = string.Format("{0}/{1}{2}", dir, oid, ext);
                    var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
                    var ok = oss.PutObject(DtoHelper.oss_bucketName, path, mss);
                    paths.Add(path);
                }
            }
            //释放内存
            GC.Collect();
            return paths;
        }

        protected string Upload(string action_dir, string fileInput = "file", bool use_time = false) {
            if (Request.Files.Count == 0)
                return null;

            var file = Request.Files[fileInput];
            if (file == null)
                return null;
            var time = DateTime.Now.Date;

            var dir = string.Format("{0}", action_dir).TrimEnd('/');
            if (use_time) dir += "/" + (time.Ticks).ToString().TrimEnd('0');

            string ext = Path.GetExtension(file.FileName);

            byte[] file_byte = new byte[file.ContentLength];
            file.InputStream.Read(file_byte, 0, file.ContentLength);

            var fileType = FileValid.GetFileType(file_byte);
            if (fileType != FileExtension.GIF && fileType != FileExtension.JPG && fileType != FileExtension.PNG)
                throw new ServerErrorException("上传文件格式不正确");
            MemoryStream mss = new MemoryStream(file_byte);
            var oid = Guid.NewGuid().ToString("N");
            var path = string.Format("{0}/{1}{2}", dir, oid, ext);
            var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
            var ok = oss.PutObject(DtoHelper.oss_bucketName, path, mss);
            //释放内存
            GC.Collect();
            return path;
        }

        /// <summary>
        /// 根据key获取cookie值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string GetCookieValue(string key) {
            string result = "";
            if (Request.Cookies.AllKeys.Contains(key)) {
                result = Request.Cookies[key].Value;
                if (!string.IsNullOrEmpty(result))
                    result = System.Text.Encoding.Default.GetString(Convert.FromBase64String(result));
            }
            return result;
        }

        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress() {
            string userHostAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(userHostAddress)) {
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    userHostAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            }
            if (string.IsNullOrEmpty(userHostAddress)) {
                userHostAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip) {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
    //public class userCookie {
    //    public userCookie() { roles = new List<string>(); }
    //    public long user_id { get; set; }
    //    public List<string> roles { get; set; }
    //    /// <summary>
    //    /// 管理员的角色，如果是空就是超级权限，如果非空就按值查询
    //    /// </summary>
    //    public long? role_id { get; set; }
    //}

    public class site {
#if DEBUG
        public string img_url = "http://testimg.epalpay.cn/";
#else
        public string img_url = "http://gimg.epalpay.cn/";
#endif
    }


}